//筛选
var fil_li = document.querySelectorAll(".filtrateSort ul>li");
var tap_li = document.querySelectorAll(".tap>ul>li");

function sift(className, styleName) {
	Array.from(className).forEach(function(itemA) {
		var arr = itemA.parentNode.children;
		itemA.onclick = function() {
			Array.from(arr).forEach(function(itemB) {
				itemB.classList.remove(styleName);
			})
			this.classList.add(styleName);
		}
	})
}
sift(tap_li, "tapStyle");
sift(fil_li, "azonic");

//价格排序
var ascSort = document.querySelector(".ascSort");
var descSort = document.querySelector(".descSort");
var product_all = document.querySelector(".product_item>ul");
ascSort.onclick = function() {
	var index = this.getAttribute("_index");
	pcommoditySort(index);
};
descSort.onclick = function() {
	var index = this.getAttribute("_index");
	pcommoditySort(index);
};

function pcommoditySort(index) {
	var product_item = document.querySelectorAll(".product_item li");
	var product_arr = Array.from(product_item)
	console.log(product_arr)
	product_arr.sort(function(itemA, itemB) {
		var priceA = itemA.querySelector(".product_price").innerText;
		var priceB = itemB.querySelector(".product_price").innerText
		priceA = Number(priceA.replace(/￥/g, ''));
		priceB = Number(priceB.replace(/￥/g, ''));
		return index * (priceA - priceB);
	})
	product_all.innerHTML = '';
	product_arr.forEach(function(item, index) {
		product_all.appendChild(item);
	})
}


$(".product_item li").each(function(index, item) {
	$(item).attr("id", index + 1)
})

$(document).ready(function() {
	var goodsObj = countPrice();
	$(".cartNum").text(goodsObj.goodsNum);
});



//添加购物车
$(".btn_default").click(function() {
	var $goodsLi = $(this).parent().parent();

	var goodsId = $(this).parent().parent().attr("id");
	var goodsImg = $goodsLi.find(".product_img img").attr("src");
	var goodsName = $goodsLi.find(".product_title").text().trim();
	var goodsInfo = $goodsLi.find(".product_info").text().trim();
	var goodsPrice = $goodsLi.find(".product_price").text().trim();
var goodsArr = [];
	var goods = {
		goodsId: goodsId,
		goodsImg: goodsImg,
		goodsName: goodsName,
		goodsInfo: goodsInfo,
		goodsPrice: goodsPrice,
		num: 1
	}
    var cartIndex = 0;
	

	var cart = getCookie("cart");
	if (cart) {
		var goodsArr = JSON.parse(cart); //转换成js对象
	} else {
		var goodsArr = [];
	};
	var isExist = false;
	goodsArr.forEach(function(item,index) {
		if (item.goodsId == goodsId) {
			isExist = true;
			item.num++;
			cartIndex = index;
		}
	});
	
	if (!isExist) {
		// 添加进cart
		goodsArr.push(goods);
		cartIndex = goodsArr.length-1;
	}
	setCookie("cart", JSON.stringify(goodsArr));
	setCookie("newGoodsIndex", JSON.stringify(cartIndex));
	var cartArr = JSON.parse(getCookie("cart"));
	var cartNum = 0;
	cartArr.forEach(function(item){
		cartNum = cartNum+Number(item.num)
		$(".cartNum").text(cartNum);
	})
})
